import mechanize
import cookielib
import os
 
#Get the server name and code
#path = os.path.join("D:", "yyy.txt")
#command = "sesictrl -n > yyy.txt"

"""
cur_dir = os.getcwd()
print os.path.join("/","opt","hfs11.0.581")
os.chdir(os.path.join("/","opt","hfs11.0.581"))
os.system("ls")
os.system("source houdini_setup")
os.chdir(cur_dir)
"""

command = "/usr/lib/sesi/sesictrl -n > yyy.txt"
ubuntu_command = "/opt/hfs11.0.581/houdini/sbin/sesictrl -n > yyy.txt"
os.system(ubuntu_command)
f = open("yyy.txt", "r")
contents = f.read()
f.close()
#print "Printing\n", contents
contents = contents.split()
server_name = contents[-2]
server_code = contents[-1]

# Browser
br = mechanize.Browser()

# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)

# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

# Want debugging messages?
#br.set_debug_http(True)
#br.set_debug_redirects(True)
#br.set_debug_responses(True)

# User-Agent (this is cheating, ok?)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

# Open some site, let's pick a random one, the first that pops in mind:
r = br.open('http://license.sidefx.com/get_nc_license.php')

# Select the first (index zero) form
br.select_form(nr=0)
br.form['servername']=server_name
br.form['servercode']=server_code
br.submit()
html = br.response().read()
html = html.replace("&nbsp;", " ")

# Extract the lines
split_html = html.split("code")
line1 = split_html[1][1:-2]
line2 = split_html[3][1:-2]
line3 = split_html[5][1:-2]

# Write license file
lic_win_path = "C:/Windows/keys/"
lic_linux_path = os.path.join("/", "usr", "lib", "sesi")
lic_filename = "licenses.local"
f = open(os.path.join(lic_linux_path, lic_filename), 'w')
f.write(line1 + "\n\n")
f.write(line2 + "\n\n")
f.write(line3 + "\n\n")
f.close()

#Printing
print "==========================="
print line1
print "==========================="
print line2
print "==========================="
print line3
print "==========================="








